package com.example.demo.controller;

import com.example.demo.entity.CultureBackgroundDetail;
import com.example.demo.entity.Instrument;
import com.example.demo.service.CultureBackgroundDetailService;
import com.example.demo.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/culture-background-detail")
public class CultureBackgroundDetailController {

    @Autowired
    private CultureBackgroundDetailService service;

    @GetMapping("/hot")
    public List<CultureBackgroundDetail> getHotBackground() {
        return service.getHotBackground();
    }

    @PostMapping("/upload")
    public String getPicFileName(MultipartFile file){
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);
        String typeName = oldFileName.substring(oldFileName.lastIndexOf('.'));
        String filePath = FileUtil.getUploadFilePath();
        System.out.println(typeName);
        String newFileName = System.currentTimeMillis()+typeName;

        try {
            FileUtil.uploadFile(file.getBytes(),filePath,newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }

    @GetMapping("/all")
    public List<CultureBackgroundDetail> getAllDetails() {
        return service.getAllDetails();
    }

    @GetMapping("/search")
    public List<CultureBackgroundDetail> searchByTitle(@RequestParam String title) {
        return service.searchByTitle(title);
    }

    @PostMapping("/add")
    public String addDetail(@RequestBody CultureBackgroundDetail detail) {
        service.addDetail(detail);
        return "Detail added successfully!";
    }

    @PutMapping("/update")
    public String updateDetail(@RequestBody CultureBackgroundDetail detail) {
        service.updateDetail(detail);
        return "Detail updated successfully!";
    }

    @DeleteMapping("/delete/{id}")
    public String deleteDetail(@PathVariable Integer id) {
        service.deleteDetail(id);
        return "Detail deleted successfully!";
    }

    @GetMapping("/{id}")
    public ResponseEntity<CultureBackgroundDetail> getCultureBackgroundDetailById(@PathVariable Integer id) {
        // 增加浏览量
        service.incrementViewCount(id);
        // 获取详细信息并返回
        CultureBackgroundDetail detail = service.getDetailById(id);
        return ResponseEntity.ok(detail);
    }
}

